package com.example.juc.big_talk_concurrent.chapter4.article4;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {
    static Map<String, Object> map = new HashMap<>();
    // 读写锁
    static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    // 读锁
    static Lock readLock = rwl.readLock();
    // 写锁
    static Lock writeLock = rwl.writeLock();

    // 获取一个 key 对应的 value
    public static final Object get(String key) {
        // 加读锁
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            // 释放读锁
            readLock.unlock();
        }
    }

    // 设置 key 对应的 value，并返回旧的 value
    public static final Object put(String key, Object value) {
        // 加写锁
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            // 释放写锁
            writeLock.unlock();
        }
    }


}

